<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/9 0009
 * Time: 14:41
 */
namespace hook;
use service\FileService;
use think\Db;

/**
 * 融云行为类
 * Class AccessAuth
 * @package hook
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/05/12 11:59
 */
class RongCloud
{

    /**
     * 当前请求对象
     * @var Request
     */
    protected $request;

    /**
     * 行为入口
     * @param $params
     */
    public function run(&$params){}


    /**
     * 存储注册用户详细信息
     * @param $params
     */
    public function saveUserInfo(&$params){
        if($params){
            $data = FileService::readFile('users.json');
            if($data){
                $data = (array)json_decode($data);
                if(isset($data[$params['uid']]) && !empty($data[$params['uid']])){
                    if($data[$params['uid']]->name = $params['name'] && $data[$params['uid']]->portrait = $params['portrait']){
                        return true;
                    }
                }
                $data[$params['uid']] = (object)$params;
            }else{
                //生成文件
                $data[$params['uid']] = $params;
            }
            return $rst = FileService::save('users.json',json_encode($data));
        }
    }

    /**
     * 存储用户建群信息
     * @param $params
     */
    public function saveUserGroup(&$params){
        if($params){
            $where = [
                'group_id' => $params['group_id'],
                'uid' => ['in',$params['user_id']]
            ];
            if($group = Db::name('rcloud_group')->where($where)->find()){
                Db::name('rcloud_group')->where($where)->delete();
            }
            $data = [];
            if($params['user_id']){
                foreach($params['user_id'] as &$v){
                    $data[] = [
                        'uid' => $v,
                        'group_id' => $params['group_id'],
                        'group_name' => $params['group_name'],
                        'owner' => $params['owner']
                    ];
                }
            }
            return Db::name('rcloud_group')->insertAll($data);
        }
    }


    /**
     * 删除群中退群用户信息
     * @param $params
     */
    public function delGroupUser(&$params){
        if($params){
            $where = [
                'group_id' => $params['group_id'],
                'uid' => ['in',$params['user_id']]
            ];
            return Db::name('rcloud_group')->where($where)->delete();
        }
    }

    /**
     * 解散群
     * @param $params
     */
    public function delGroup(&$params){
        if($params){
            $where = [
                'group_id' => $params['group_id'],
                'owner' => ['in',$params['user_id']]
            ];
            return Db::name('rcloud_group')->where($where)->delete();
        }
    }

}
